﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using JumbotPay.API.Bdpay;
namespace JumbotPay.WebFile.Bdpay
{
    /// <summary>
    /// 创建该页面文件时，请留心该页面文件是可以对其进行美工处理的，原因在于支付完成以后，当前窗口会从支付宝的页面跳转回这个页面。
    /// 该页面称作“返回页”，是同步被支付宝服务器所调用，可当作是支付完成后的提示信息页，如“您的某某某订单，多少金额已支付成功”。
    /// </summary>
    public partial class _return_url : JumbotPay.UI.BasicPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LogWriter logwriter = new LogWriter();
            string getStrPre = Request.QueryString.ToString();
            logwriter.appendToLog("notifyUrl支付返回地址栏数据：" + getStrPre, Server.MapPath("~/Logs/NetLogBFB.log"));
            string getStr = System.Web.HttpUtility.UrlDecode(getStrPre, System.Text.Encoding.GetEncoding("GBK"));
            string[] resultStrTemp = getStr.Split('&');
            string[] resultStr = new String[resultStrTemp.Length - 1];
            string signtemp = resultStrTemp[resultStrTemp.LongLength - 1];
            int stateInd = signtemp.IndexOf("=") + 1;
            string sign = signtemp.Substring(stateInd);
            logwriter.appendToLog("百度钱包返回的签名串：" + sign, Server.MapPath("~/Logs/NetLogBFB.log"));

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < resultStrTemp.Length - 1; i++)
            {
                resultStr[i] = resultStrTemp[i];
                sb.AppendLine(resultStr[i]);
            }
            logwriter.appendToLog("百度钱包返回参数", Server.MapPath("~/Logs/NetLogBFB.log"));
            logwriter.appendToLog(sb.ToString(), Server.MapPath("~/Logs/NetLogBFB.log"));
            String Localsign = new JumbotPay.API.Bdpay.Common().make_sign(resultStr);
            logwriter.appendToLog("本地签名串：" + Localsign, Server.MapPath("~/Logs/NetLogBFB.log"));
            logwriter.appendToLog("百度钱包返回签名串：" + sign, Server.MapPath("~/Logs/NetLogBFB.log"));

            int pay_status = 1;//默认支付失败
            //比对签名
            string pay_order_id = Request.QueryString["bfb_order_no"];         //百付宝交易号
            string out_trade_no = Request.QueryString["order_no"];	        //获取订单号
            string total_amount = Request.QueryString["total_amount"];            //获取总金额
            string appid = Request.QueryString["extra"];
            if (Request["pay_result"].Equals("1"))
            {
                pay_status = 0;
                Response.Write("返回签名册" + sign.Trim());
                Response.Write("本地验证签名串" + Localsign.Trim());
                if (sign.Trim().Equals(Localsign.Trim()))
                {

                    if (new JumbotPay.DAL.OrderDAL().UpdateOrder("bdpay", out_trade_no, pay_order_id))
                    {
                    }
                    /**
                     * 3、支付通知结果的回执
                     * 作用：	收到通知，并验证通过，向百度钱包发起回执。百度钱包GET请求商户的return_url页面，商户这边的响应
                     * 中必须包含以下部分，百度钱包只有接收到特定的响应信息后，才能确认商户已经收到通知，并验证通过。这样
                     * 百度钱包才不会再向商户发送支付结果通知
                     */
                    Response.Write("<HTML><head>");
                    Response.Write("<meta name=\"VIP_BFB_PAYMENT\" content=\"BAIFUBAO\">");
                    Response.Write("</head>");
                    Response.Write("<body>");
                    Response.Write("支付成功，验签通过" + "订单号：" + Request["order_no"] + "<br/>");
                    Response.Write("百度钱包返回的签名串 :" + sign + "<br/>");
                    Response.Write("本地生成的签名串     :" + Localsign + "<br/>");
                    Response.Write("</body></html>");
                    /**
                     *  重要：接收到百度钱包的后台通知后，商户须返回特定的HTML页面。该页面应该满足以下要求：
                     *	重要：HTML头部须包括<meta name="VIP_BFB_PAYMENT" content="BAIFUBAO">
                     *	重要：商户可以通过百度钱包订单查询接口再次查询订单状态，二次校验
                     *	重要：该查询接口存在一定的延迟，商户可以不用二次校验，信任后台的支付结果通知便行
                     */
                }
                else if (!sign.Trim().Equals(Localsign.Trim()))
                {
                    Response.Write("支付成功，验签失败" + "<br/>");
                    logwriter.appendToLog("支付成功，验签失败", Server.MapPath("~/Logs/NetLogBFB.log"));
                }
            }
            else
            {
                Response.Write("支付失败" + "<br/>");
                logwriter.appendToLog("支付失败", Server.MapPath("~/Logs/NetLogBFB.log"));
            }
            doh.Reset();
            doh.ConditionExpress = "appid=@appid";
            doh.AddConditionParameter("@appid", appid);
            object[] value = doh.GetFields("jpay_app", "return_url");
            if (value != null)
            {
                string _return_url = value[0].ToString();
                string key = new JumbotPay.DAL.AppDAL().GetKey(appid);
                doh.Reset();
                doh.ConditionExpress = "out_trade_no=@out_trade_no";
                doh.AddConditionParameter("@out_trade_no", out_trade_no);
                string order_id = doh.GetField("jpay_order", "order_id").ToString();//根据流水号反推业务订单号
                string[] array1 ={
			    "order_id="+order_id,
                "pay_status="+pay_status,
                "pay_order_id="+out_trade_no
				};
                string sign1 = JumbotPay.Utils.Strings.GetSign(array1, key);
                Response.Redirect(_return_url + "?" + JumbotPay.Utils.Strings.GetParaStr(array1, sign1));
            }
            else
            {
                Response.Write("app无效");
            }
        }
    }
}